package com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.browser.editor.detail.guide;

import java.util.List;

import com.google.code.irouter.portal.client.AppConstants;
import com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.browser.editor.Detail;
import com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.browser.editor.detail.guide.target.Command;
import com.google.code.irouter.portal.client.rpc.collector.CollectorResult;
import com.google.code.irouter.portal.client.rpc.collector.CollectorService;
import com.google.code.irouter.portal.client.rpc.collector.CollectorServiceAsync;
import com.google.code.irouter.portal.client.rpc.guide.GuideResult;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.SortDir;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.GroupingStore;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.SortState;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.dd.DragData;
import com.gwtext.client.dd.DragSource;
import com.gwtext.client.dd.DropTarget;
import com.gwtext.client.dd.DropTargetConfig;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridDragData;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.GroupingView;

public final class Target extends GridPanel {
	
	private static final AppConstants CONSTANTS = GWT.create(AppConstants.class);
	private final CollectorServiceAsync collectorService = GWT.create(CollectorService.class);
	
	private RecordDef recordDef;
	
	public Target() {
		super();
		this.setId(Target.class.getName());

		recordDef = new RecordDef(  
                new FieldDef[]{  
                        new StringFieldDef("name"),  
                        new StringFieldDef("detector"),  
                        new StringFieldDef("resource"),  
                        new StringFieldDef("fixedLink"),
                        new StringFieldDef("key")
                }  
        );  

        MemoryProxy proxy = new MemoryProxy(new Object[0][0]);  
  
        ArrayReader reader = new ArrayReader(recordDef);  
        GroupingStore store = new GroupingStore();  
        store.setReader(reader);  
        store.setDataProxy(proxy);  
        store.setSortInfo(new SortState("name", SortDir.ASC));  
        store.setGroupField("detector");
        store.load();  
        this.setStore(store);  
  
  
        ColumnConfig[] columns = new ColumnConfig[]{  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_editor_detail_guide_target_column_name(), 
                		"name", 
                		160,
                		true, 
                		null, 
                		"target"
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_editor_detail_guide_target_column_detector(), 
                		"detector", 
                		160,
                		true
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_editor_detail_guide_target_column_resource(), 
                		"resource", 
                		160,
                		false
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_editor_detail_guide_target_column_fixedLink(), 
                		"fixedLink", 
                		160,
                		false
                ) 
        };  
  
        ColumnModel columnModel = new ColumnModel(columns);  
        this.setColumnModel(columnModel);
        this.setEnableDragDrop(true);
        this.setDdGroup(Source.GROUP);
        this.setStripeRows(true);  
        this.setAutoExpandColumn("name");
        this.setBottomToolbar(new Command());
        
        GroupingView gridView = new GroupingView();  
        gridView.setForceFit(true);  
        gridView.setGroupTextTpl("{text} ({[values.rs.length]} {[values.rs.length > 1 ? \"Items\" : \"Item\"]})");  
        this.setView(gridView);  
        this.setAnimCollapse(false); 

        DropTargetConfig cfg = new DropTargetConfig();
        cfg.setdDdGroup(Source.GROUP);

        new DropTarget(this, cfg) {
	        @Override 
	        public boolean notifyDrop(DragSource source, EventObject e, DragData data) {
	        	GridDragData gridDragData = (GridDragData) data;  
	            Record[] records = gridDragData.getSelections();
	            for (int i = 0; i < records.length; i++) {
	            	Record record = records[i];
	            	if(getStore().indexOfId(record.getAsString("key")) == -1) {
	            		Record row = recordDef.createRecord(
		                		new Object[]{
		                				record.getAsString("name"),
		                				record.getAsString("detector"),
		                				record.getAsString("resource"),
		                				record.getAsString("fixedLink"),
		                				record.getAsString("key")
		                		}
		                );
		                getStore().insert(0, row);
	            	}
	            }
	            return true;
	        }
        };
	}
	
	public void remove() {
		Record[] records = this.getSelectionModel().getSelections();
		for(Record record : records) {
			this.getStore().remove(record);
		}
	}
	
	public void reset() {
        MemoryProxy proxy = new MemoryProxy(new Object[0][0]);
        ArrayReader reader = new ArrayReader(recordDef);
        GroupingStore store = new GroupingStore();
        store.setReader(reader);
        store.setDataProxy(proxy);
        store.setSortInfo(new SortState("name", SortDir.ASC));
        store.setGroupField("detector");
        store.load();
        this.reconfigure(store, this.getColumnModel());
	}
	
	public void load(String id) {		
		collectorService.get(id, new AsyncCallback<CollectorResult>() {
			public void onFailure(Throwable caught) {
				// TODO
			}

			public void onSuccess(CollectorResult collectorResult) {
				if(collectorResult != null) {
					List<GuideResult> guideResultList = collectorResult.getGuides();
					if(guideResultList.size() > 0) {
						Object[][] guideArray = new Object[guideResultList.size()][5];
						int index = 0;
						for(GuideResult guide : guideResultList) {
							Object[] guideItem = new Object[5];
							guideItem[0] = guide.getName();
							guideItem[1] = guide.getDetector();
							guideItem[2] = guide.getResource();
							guideItem[3] = guide.getFixedLink();
							guideItem[4] = String.valueOf(guide.getId());
							guideArray[index] = guideItem;
							index++;							
						}
						MemoryProxy proxy = new MemoryProxy(guideArray);						  
				        ArrayReader reader = new ArrayReader(recordDef);  
				        GroupingStore store = new GroupingStore();  
				        store.setReader(reader);  
				        store.setDataProxy(proxy);  
				        store.setSortInfo(new SortState("name", SortDir.ASC));  
				        store.setGroupField("detector");
				        store.load();  
				        reconfigure(store, getColumnModel());
					}
					((Detail) Ext.getCmp(Detail.class.getName())).setGlobalEnable(Detail.Children.GUIDE);
				}			
			}
		});
	}

}
